﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CQIE.TES.IDAL;
using CQIE.TES.IService;
using CQIE.TES.Model;
using CQIE.TES.WEB.USER.Models;

namespace CQIE.TES.Service
{
    public class RecordService: IRecordService
    {
        private readonly IRecordDAL _dal;
        private readonly IStudentDAL _studentDal;
        private readonly ITeacherDAL _teacherDal;
        private readonly IStudyYearDAL _studyYearDal;
        private readonly ICourseDAL _courseDal;
        public RecordService(IRecordDAL dal, IStudentDAL studentDal, ITeacherDAL teacherDal, IStudyYearDAL studyYearDal, ICourseDAL courseDal)
        {
            this._dal = dal;
            this._studentDal = studentDal;
            this._teacherDal = teacherDal;
            _studyYearDal = studyYearDal;
            _courseDal = courseDal;
        }

        #region 评教相关

        public bool Record(int evaId, int teacherid, int courseId, int studentId, List<int> answerList, List<int> question)
        {
            return _dal.SaveStudentRecord(evaId, teacherid, courseId,studentId,answerList,question);
        }

        public List<Record> IsRecorded(int evaid, int teacherid, int courseId, int sid)
        {
            var model = _studentDal.FindByID(sid);
            return _dal.IsRecorded(evaid, teacherid, courseId, model.StudentNumber);
        }

        public List<Record> IsRecorded(int evaId, int teacherId, int aimTeacherId, ENUM_EVA_TYPE mode)
        {
            var teacher = _teacherDal.FindById(teacherId);
            var aimTeacher = _teacherDal.FindById(aimTeacherId);

            return _dal.IsRecorded(evaId, teacher, aimTeacher.ID,mode);
        }

        public List<Record> IsRecorded(int evaId, int teacherId)
        {
            var teacher = _teacherDal.FindById(teacherId);
            return _dal.IsRecorded(evaId, teacher);
        }

        public bool Record(int evaId, int teacherId, int aimTeacherId, List<int> answerList, List<int> questionList,
            ENUM_EVA_TYPE mode)
        {
            var teacher = _teacherDal.FindById(teacherId);
            var aimTeacher = _teacherDal.FindById(aimTeacherId);

            return _dal.SaveDepartmentRecord(evaId,teacher.WorkNumber,aimTeacher.ID,answerList,questionList, mode);
        }

        public bool TeacherOtherRecord(int evaId, int teacherId, int aimTeacherId, List<int> answerList, List<int> questionList)
        {
            var teacher = _teacherDal.FindById(teacherId);
            var aimTeacher = _teacherDal.FindById(aimTeacherId);

            return _dal.SaveTeacherOtherRecord(evaId, teacher.WorkNumber, aimTeacher.ID, answerList, questionList);
        }

        public bool Record(int evaId, int teacherId, List<int> answerList, List<int> questionList)
        {
            var teacher = _teacherDal.FindById(teacherId);

            return _dal.SaveTeacherSelfRecord(evaId,teacher.ID, teacher.WorkNumber, answerList, questionList);
        }

        #endregion

        #region 查看结果相关

        public object GetEvaTrend()
        {
            return _dal.GetEvaTrend();
        }

        public object GetDetailAllInfo(int tid)
        {
            // 将方法包装为委托
//            Func<object> f1 = () => TeacherYearTrend(tid);
//            Func<object> f2 = () => GetClassScore(tid);
//            Func<List<object>> f3 = () => GetCourseScore(tid);
//            Func<object> f4 = () => GetLeftDownData(tid);

            var t = _teacherDal.FindById(tid);

            //IAsyncResult t1 = f1.BeginInvoke(null, null);
            //IAsyncResult t2 = f2.BeginInvoke(null, null);
            //IAsyncResult t3 = f3.BeginInvoke(null, null);
            //IAsyncResult t4 = f4.BeginInvoke(null, null);
            //
            //bool b1 = t3.AsyncWaitHandle.WaitOne();
            //bool b2 = t2.AsyncWaitHandle.WaitOne();
            //bool b3 = t4.AsyncWaitHandle.WaitOne();
            //bool b4 = t1.AsyncWaitHandle.WaitOne();
            var rightData = TeacherYearTrend(tid);
            var leftCenter = GetCourseScore(tid);
            var leftDown = GetLeftDownData(tid);
            var studyYear = _studyYearDal.GetStudyYearsInfo().Select(r => r.Name).ToList();

            return new {
                //rightData = TeacherYearTrend(tid),
                //leftAbove = GetClassScore(tid),
                //leftCenter = GetCourseScore(tid),
                //leftDown = GetLeftDownData(tid),
                rightData,
                leftCenter,
                leftDown,
                studyYear,
                teacherId = t.ID,
                teacherName = t.Name
            };

            
        }

        public object GetTableData(int limit, int page, string searchString, out int count)
        {
            return _dal.GetTableData(limit, page-1, searchString,out count);
        }

        /// <summary>
        /// 获取左下数据   学生评教、教研室、教师互评
        /// </summary>
        /// <param name="teacherId"></param>
        /// <returns></returns>
        private object GetLeftDownData(int teacherId)
        {
            var res = new
            {
                studentEva = _dal.CalcEvaTypeNum(teacherId, ENUM_EVA_TYPE.Student),
                courseLeaderEva = _dal.CalcEvaTypeNum(teacherId, ENUM_EVA_TYPE.CourseLeader),
                teacherEva = _dal.CalcEvaTypeNum(teacherId, ENUM_EVA_TYPE.Teacher),
                departMentEva = _dal.CalcEvaTypeNum(teacherId,ENUM_EVA_TYPE.Department),
                selfEva = _dal.CalcEvaTypeNum(teacherId,ENUM_EVA_TYPE.Self)
            };
            return res;
        }

        /// <summary>
        /// 大屏右边所有数据
        /// 教师学年综合评教走势 以及优秀···评级次数  总成绩
        /// </summary>
        /// <param name="teacherId">教师ID</param>
        /// <returns>
        /// Trend => ScoreTrend => [58,89,···](每年总成绩)
        /// LevelNum => TeacherLevelNum => [{name:'优秀',value:3},···]
        /// TotalScore => double 总成绩
        /// </returns>
        private object TeacherYearTrend(int teacherId)
        {
            List<object> teacherLevelNum = new List<object>();
            List<double> scoreTrend = _dal.GetTeacherScoreTrend(teacherId);

            teacherLevelNum.Add(new { name = "优秀", value = scoreTrend.Count(r => r >= 50) });
            teacherLevelNum.Add(new { name = "良好", value = scoreTrend.Count(r => r >= 40 && r < 50) });
            teacherLevelNum.Add(new { name = "一般", value = scoreTrend.Count(r => r >= 25 && r < 40) });
            teacherLevelNum.Add(new { name = "较差", value = scoreTrend.Count(r => r < 25) });
            return new
            {
                Trend = scoreTrend,
                LevelNum = teacherLevelNum,
                TotalScore = Math.Round(scoreTrend.Average(), 2)
            };
        }

        /// <summary>
        /// 获取教师所有课程平均分 左中
        /// </summary>
        /// <param name="teacherId"></param>
        /// <returns>[{name:课程,value:分数}]</returns>
        private object GetCourseScore(int teacherId)
        {
            return _dal.GetCourseGrade(teacherId);
        }


        /// <summary>
        /// 获取班级对教师的评教   左上
        /// </summary>
        /// <param name="teacherId"></param>
        /// <returns></returns>
        [Obsolete("由于性能原因放弃该方法")]
        private object GetClassScore(int teacherId)
        {
            return _dal.GetClassScore(teacherId);
        }

        #endregion
    }
}
